<template>
  <div class="login-detail">
    <el-form ref="formRef" :rules="rules" :model="userForm" label-width="80px">

      <el-row>
        <el-col :span="10">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="userForm.username" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col :span="10">
          <el-form-item label="密码" prop="password">
            <el-input v-model="userForm.password" type="password" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="10">
          <el-form-item>
            <el-button type="primary" plain @click="cancleBack">取消</el-button>
            <el-button type="primary" plain @click="onSubmit">立即更新</el-button>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script>
import { getUserSimpleDetailRequest, uploadUserSimpleDetailRequest } from '@/api/employees'
export default {
  data() {
    return {
      // 表单数据初始化
      userForm: {
        username: '',
        password: ''
      },
      // 定义校验规则
      rules: {
        username: [
          { required: true, message: '请输入 后再进行提交', trigger: 'blur' },
          { min: 2, max: 4, message: '请输入 2 ~ 4 位姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入 后再进行提交', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserSimpleDetail() // 获取员工基本信息
  },
  methods: {
    // ^ ==================== 请求 ====================
    // 请求- 获取员工基本信息
    async getUserSimpleDetail() {
      try {
        const res = await getUserSimpleDetailRequest(this.$route.query?.id)
        if (res.success) {
          this.userForm = res.data // 赋值渲染
        } else {
          this.$message.error('获取员工基本信息失败!')
        }
      } catch (error) {
        console.log('获取员工基本信息失败', error)
      }
    },
    // 请求 - 更新用户基本信息
    async uploadUserSimpleDetail() {
      try {
        const res = await uploadUserSimpleDetailRequest(this.userForm)
        // 业务代码成功后做些什么
        if (res.success) {
          this.$message.success('修改用户基本信息成功!')
          console.log(res)
          this.$router.back() // 将页面跳回上一个路由地址页面, 由于组件创建会自动执行生命周期所以不需要重新渲染页面
          return
        }
        this.$message.error('更新用户基本信息失败!')
      } catch (error) {
        console.log('更新用户基本信息失败!', error)
      }
    },
    // ^ ==================== 事件 ====================
    // 事件 - 提交
    onSubmit() { // 兜底校验
      this.$refs.formRef.validate(val => {
        if (!val) return this.$message.error('校验失败, 请重新输入后再提交')
        // 校验通过, 调用函数发送请求
        this.uploadUserSimpleDetail()
      })
    },
    // 取消操作, 路由回退
    cancleBack() {
      this.$router.back()
    }
  }
}
</script>

<style>
</style>
